package cn.aias.rbac.domain.model;

import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.Set;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"users", "permissions"}) // Exclude Hibernate-managed collections
@Entity
@Table(name = "roles")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String roleName;    // 角色名称（如ADMIN、EDITOR）
    private String description; // 角色描述（可选）

    // 创建时间（仅插入时赋值）
    @CreationTimestamp
    private LocalDateTime createTime;

    // 修改时间（每次更新时自动刷新）
    @UpdateTimestamp
    private LocalDateTime updateTime;

    // 用户-角色双向多对多（反向映射User的roles字段）
    @ManyToMany(mappedBy = "roles")
    @JSONField(serialize = false) // Skip this field during JSON serialization
    private Set<User> users;

    // 角色-权限多对多（关联Permission实体）
    @ManyToMany
    @JoinTable(
            name = "role_permissions",
            joinColumns = @JoinColumn(name = "role_id"),
            inverseJoinColumns = @JoinColumn(name = "permission_id")
    )
    // 序列化时忽略未初始化的 permissions 集合
    @JSONField(serialize = false)
//    @JsonIgnore
    private Set<Permission> permissions;


}
